<script setup lang="ts">
import type { LoginRequestData } from "./apis/type"
import Description from "@@/components/Description.vue"
import { showFailToast } from "vant"
import { useUserStore } from "@/pinia/stores/user"
import { loginApi } from "./apis"

const router = useRouter()

const userStore = useUserStore()

const loading = ref(false)

const loginFormData: LoginRequestData = reactive({
  tenantName: "芋道源码",
  username: "",
  password: "",
  rememberMe: true
})

function onSubmit() {
  loading.value = true
  loginApi(loginFormData).then(({ data }) => {
    userStore.setToken(data.accessToken)
    userStore.setUsername(loginFormData.username)
    userStore.setPassword(loginFormData.password)
    userStore.setRemember(loginFormData.rememberMe)
    router.push("/")
  }).catch(() => {
    showFailToast("Username or password is incorrect")
    loginFormData.password = ""
  }).finally(() => {
    loading.value = false
  })
}

onMounted(() => {
  if (userStore.getRemember()) {
    loginFormData.username = <string>userStore.getUsername()
    loginFormData.password = <string>userStore.getPassword()
    loginFormData.rememberMe = true
  }
})
</script>

<template>
  <div un-h-full un-flex-center un-flex-col un-select-none>
    <Description un-mb-20px />
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="loginFormData.username"
          name="username"
          label="Username"
          size="large"
          :rules="[{ required: true, message: 'Please input your username' }]"
        />
        <van-field
          v-model="loginFormData.password"
          type="password"
          name="password"
          label="Password"
          size="large"
          :rules="[{ required: true, message: 'Please input your password' }]"
        />
        <van-cell clickable title="Remember me">
          <template #right-icon>
            <van-checkbox v-model="loginFormData.rememberMe" />
          </template>
        </van-cell>
      </van-cell-group>

      <div un-mx-16px un-my-32px>
        <van-button
          :loading="loading"
          type="primary"
          native-type="submit"
          size="large"
          round
          block
        >
          Login
        </van-button>
      </div>
    </van-form>
  </div>
</template>
